package com.qf.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * 改造工具类: 使用druid连接池改造
 */
public class JDBCUtils2 {
    private static  DataSource dataSource=null;
    static {
        try {
            //1.创建properties对象
            Properties properties = new Properties();
            //2.获取配置文件的 字节输入流
            InputStream inputStream=JDBCUtils2.class.getClassLoader().
                    getResourceAsStream("db.properties");
            //3.加载配置文件
            properties.load(inputStream);
            //4.通过druidfactory获取连接池对象
          dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //0.提供一个方法获取连接对象
    public  static DataSource getDs(){
       return  dataSource;
    }
    //1.提供一个方法获取连接对象
    public  static Connection getConnectionFromPool(){
        Connection connection=null;
        try {
            connection = dataSource.getConnection();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return  connection;
    }
    //2.释放资源的方法
    public static  void closeResources(Connection con, Statement stmt, ResultSet rs){
        //5.关闭资源
        try {
            if(con!=null){
                con.close();
            }
            if(stmt!=null){
                stmt.close();
            }
            if(rs!=null){
                rs.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}












